package dycloud.mabaoguo.User.controller;


import com.alibaba.fastjson.JSON;
import dycloud.demo.model.JsonResponse;
import dycloud.mabaoguo.User.model.*;
import dycloud.mabaoguo.User.model.gameEnd.Get_End_UserData;
import dycloud.mabaoguo.User.model.gameEnd.Get_GameEndData;
import dycloud.mabaoguo.User.model.gameEnd.Post_End_UserData;
import dycloud.mabaoguo.User.model.gameEnd.Post_GameEndData;
import dycloud.mabaoguo.User.model.roleCambat.CombatRankingData;
import dycloud.mabaoguo.User.model.worldRank.WorldRankPlayerInfo;
import dycloud.mabaoguo.User.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


//所有用户相关操作
@RestController
@Slf4j
public class UserInfoCtrl {

    //@RequestBody GameRoleRank gameRoleRank   --请求体  Post
    //@RequestParam String sec_openid  --get  请求参数
    //请求头 自带的 参数有
    /*
    *  @PostMapping(path = "/start_game")
       public JsonResponse callContainerExample(HttpServletRequest httpRequest) {
        // 开发者可以直接通过请求头获取直播间信息,无需自行通过token置换

        // 应用id
        String appID = httpRequest.getHeader("X-TT-AppID");
        // 直播间id
        String roomID = httpRequest.getHeader("X-Room-ID");
        // 主播id
        String anchorOpenID = httpRequest.getHeader("X-Anchor-OpenID");
        // 主播头像url
        String avatarUrl = httpRequest.getHeader("X-Avatar-Url");
        // 主播昵称
        String nickName = httpRequest.getHeader("X-Nick-Name");
    * */

    /**
     * 获取 单个玩家 信息
     */
    @Autowired
    private UserInfoService userInfoService;
    @PostMapping(path = "/getUserInfo")
    public JsonResponse getUserInfo(@RequestBody Json_UserInfo userInfo) {
        log.info("UserPid --> {} <--", userInfo.playid);
        JsonResponse response = new JsonResponse();
        try {
            Json_UserInfo us = userInfoService.checkAndInsertUserInfo(userInfo);
            if (us ==null)
            {
                response.failure("MongoDB 数据库 查询玩家信息  连接异常");
                return response;
            }
            //有该玩家  查询并插入胜利点数据
            Json_UserDataInfo jd = userInfoService.getUserDataInfo(us.getPlayid());
            if (jd ==null)
            {
                response.failure("MongoDB 数据库 查询玩家数据 连接异常");
                return response;
            }
            //传输到客户端
            response.success( JSON.toJSONString(jd));
            return response;
        }catch (Exception e) {
            response.failure("MongoDB 数据库 查询 连接异常");
            return response;
        }

    }

    @GetMapping(path = "/getWinCount")
    public JsonResponse getUserWinCount(@RequestParam String playid) {
        JsonResponse response = new JsonResponse();
        try {
            long winCount = userInfoService.getUserWinCount(playid);
            //传输到客户端
            response.success( JSON.toJSONString(winCount));
            return response;
        }catch (Exception e){
            response.failure("获取胜利点 失败");
            return response;
        }

    }
    @PostMapping(path = "/setWinCount/{playid}")
    public JsonResponse setUserWinCount(@PathVariable String playid,@RequestParam long winCount) {
        JsonResponse response = new JsonResponse();
        try {
            boolean isSuccess = userInfoService.setUserWinCount(playid,winCount);
            //传输到客户端
            response.success( JSON.toJSONString(isSuccess));
            return response;
        }catch (Exception e){
            response.failure("设置 失败");
            return response;
        }

    }


    // 请求 游戏结束数据
    @PostMapping(path = "/gameEnd")
    public JsonResponse getGameEndData(@RequestBody Post_GameEndData pData) {
        JsonResponse response = new JsonResponse();
        try {
            // 创建 Get_GameEndData 实例
            Get_GameEndData getGameEndData = new Get_GameEndData();
            getGameEndData.def_Datas = new ArrayList<>();
            getGameEndData.atk_Datas = new ArrayList<>();

            // 处理攻击方数据
            if (pData.getAtk_Datas() != null) {
                for (Post_End_UserData atkData : pData.getAtk_Datas()) {
                    Get_End_UserData getAtkData = new Get_End_UserData();
                    getAtkData.setPlayid(atkData.getPlayid());

                    getAtkData.setOld_rank(atkData.getOld_worldRank());
                    //暂时 先为0  更新完胜利点进行重新整体排序后 在设置最新的 世界 排名
                    getAtkData.setNew_rank(atkData.getOld_worldRank());

                    getAtkData.setCombat(atkData.getCombat());
                    //Todo:先进行  战力相加   也是 加完之后在进行 阵营内排名  -等待当前所有玩家的战力计算完成在排序
                    userInfoService.updateOrInsertCombat(atkData.getPlayid(),atkData.getCombat(), Json_Atk_Combat.class);


                    //Todo:先进行  胜利点相加   也是 加完之后在进行世界排名  -等待当前所有玩家的胜利点计算完整在排序

                    log.info("137: old winCount {}",userInfoService.getUserWinCount(atkData.getPlayid()));
                    getAtkData.setOld_winCount(userInfoService.getUserWinCount(atkData.getPlayid()));

                    //添加 胜利点
                    userInfoService.addWinCount(atkData.getPlayid(),atkData.getAdd_winCount());

                    getAtkData.setNew_winCount(userInfoService.getUserWinCount(atkData.getPlayid()));
                    log.info("143: new winCount {}",userInfoService.getUserWinCount(atkData.getPlayid()));

                    getGameEndData.getAtk_Datas().add(getAtkData);
                }
            }

            // 处理防守方数据
            if (pData.getDef_Datas() != null) {
                for (Post_End_UserData defData : pData.getDef_Datas()) {
                    Get_End_UserData getDefData = new Get_End_UserData();
                    getDefData.setPlayid(defData.getPlayid());

                    getDefData.setOld_rank(defData.getOld_worldRank());

                    //暂时 先为0  更新完胜利点进行重新整体排序后 在设置最新的 世界 排名
                    getDefData.setNew_rank(defData.getOld_worldRank() + 1);


                    getDefData.setCombat(defData.getCombat());
                    //Todo:先进行  战力相加   也是 加完之后在进行 阵营内排名  -等待当前所有玩家的战力计算完成在排序
                    userInfoService.updateOrInsertCombat(defData.getPlayid(),defData.getCombat(), Json_Def_Combat.class);

                    //Todo:先进行  胜利点相加   也是 加完之后在进行世界排名  -等待当前所有玩家的胜利点计算完整在排序

                    log.info("169: old winCount {}",userInfoService.getUserWinCount(getDefData.getPlayid()));
                    getDefData.setOld_winCount(userInfoService.getUserWinCount(getDefData.getPlayid()));

                    //添加 胜利点
                    userInfoService.addWinCount(defData.getPlayid(),defData.getAdd_winCount());

                    getDefData.setNew_winCount(userInfoService.getUserWinCount(defData.getPlayid()));
                    log.info("176: new winCount {}",userInfoService.getUserWinCount(defData.getPlayid()));


                    getGameEndData.getDef_Datas().add(getDefData);
                }
            }
            //更新双阵营 战力排行
            userInfoService.updateAtkCombatRank();
            userInfoService.updateDefCombatRank();

            //世界  排名 进行 排序  -- 根据 胜利点  -- 所以需要先进行更新胜利点
           // userInfoService.recalculateWorldRank();

            // 获取最新的世界排名列表
            List<Json_UserDataInfo> allUsers = userInfoService.getCurrentWorldRank();

            // 为每个玩家的世界排名赋值
            for (Get_End_UserData getAtkData : getGameEndData.getAtk_Datas()) {
                Json_UserDataInfo userData = null;
                for (Json_UserDataInfo user : allUsers) {
                    if (user.getPlayid().equals(getAtkData.getPlayid())) {
                        userData = user;
                        break;
                    }
                }
                if (userData != null) {
                    // 设置玩家的最新世界排名
                    getAtkData.setNew_rank(userData.getWorldRank());
                }
            }

            for (Get_End_UserData getDefData : getGameEndData.getDef_Datas()) {
                Json_UserDataInfo userData = null;
                for (Json_UserDataInfo user : allUsers) {
                    if (user.getPlayid().equals(getDefData.getPlayid())) {
                        userData = user;
                        break;
                    }
                }
                if (userData != null) {
                    // 设置玩家的最新世界排名
                    getDefData.setNew_rank(userData.getWorldRank());
                }
            }
            // 将最终生成的数据转换为 JSON 字符串并返回
            response.success(JSON.toJSONString(getGameEndData));
            return response;

        } catch (Exception e) {
            log.error("173: MongoDB    Connect Error: {}", e.getMessage(), e);
            response.failure("173: MongoDB    Connect Error");
            return response;
        }
    }


    @GetMapping(path = "/getAllWorldRank")
    public JsonResponse getAllWorldRank() {
        JsonResponse response = new JsonResponse();
        try {
           List<WorldRankPlayerInfo> allWorldData = userInfoService.getWorldRank();
            //传输到客户端
            response.success( JSON.toJSONString(allWorldData));
            return response;
        }catch (Exception e){
            response.failure("get world rank faile");
            return response;
        }
    }


    @GetMapping(path = "/getRoleCombat")
    public JsonResponse getRoleCambat() {
        JsonResponse response = new JsonResponse();
        try {
            CombatRankingData roleData = userInfoService.getCombatRankingData();
            //传输到客户端
            response.success( JSON.toJSONString(roleData));
            return response;
        }catch (Exception e){
            response.failure("get world rank faile");
            return response;
        }
    }

    @GetMapping(path = "/startGameSate")
    public JsonResponse getStartGameSate() {
        JsonResponse response = new JsonResponse();
        try {
            // 检查 MongoDB 连接状态
            boolean isConnected = userInfoService.checkDatabaseConnection();
            if (isConnected) {
                // 如果数据库连接正常，可以进一步处理游戏状态的获取逻辑
                log.info("Database connected successfully.");
                response.success(JSON.toJSONString(isConnected));

            } else {
                // 如果数据库连接失败
                log.info("Failed to connect to the database.");
                response.failure(JSON.toJSONString(isConnected));
            }
            // 传输到客户端
            return response;
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            log.error("Error: " + e.getMessage());
            response.failure("error  ");
            return response;
        }
    }

}
